package com.linys.scala.qf.day02

/**
  * 函数式编程初体验！！！
  */
object Exercise {

  def main(args: Array[String]): Unit = {
    val list0 = List(1, 3, 2, 5, -1, 8, 19, 101, 50, 4)

    val list1 = list0.map(_ * 2) //针对每个元素操作
    val list2 = list0.filter(_ % 2 == 0) //过滤
    val list3 = list0.sorted //排序
    val list4 = list3.reverse //反转
    val it = list0.grouped(3) //分组
    //println(it.toBuffer)
    val list5 = it.toList //转换
    //println(list5)
    val list6 = list5.flatten //压平
    // 切分，再压平
    val lines = List("hello java hello c++", "hello scala", "hello python")
    val words1 = lines.map(_.split(" ")).flatten //分组再压平
    val words2 = lines.flatMap(_.split(" ")) //分组压平
    //println(words2)

    //并行计算求和
    val arr = Array(1,2,3,4,5,6,7,8,9,10)
    val res0 = arr.par.sum

    //val res1 = arr.reduce(_+_)
    //val res2 = arr.reduceRight(_+_)
    //val res3 = arr.par.reduce(_+_)
    // 并行方式进行聚合
    val res4 = arr.par.reduce(_-_)
    //println(res4)

    //折叠，有初始值，无特定顺序（要理解是在每个线程初始值+1）
    val res5 = arr.par.fold(1)(_+_)
    val res8 = arr.par.fold(10)(_-_)
    //折叠，有初始值，有特定顺序
    val res6 = arr.foldLeft(0)(_-_)
    val res7 = arr.par.foldLeft(10)(_-_)
    //println(res8)

    //聚合
    val list7 = List(List(1,2,3), List(3,4,5), List(2), List(10))
    val list8 = List(List(List(1),2,3), List(3,4,5), List(2), List(10))
    //val res = list7.flatten.reduce(_+_)
    println(list7)
    val res9 = list7.aggregate(0)(_+_.sum, _+_)
    println(res9)


    val l1 = List(5,6,7,8)
    val l2 = List(1,2,4,5,6)
    //并集
    val res10 =  l1 union l2
    println(res10)
    //交集
    val res11 =  l1 intersect l2
    println(res11)
    //差集
    val res12 =  l1 diff l2
    val res13 =  l2 diff l1
    println(res12)
    println(res13)


  }

}
